import axios from 'axios';
import baseURL from './BaseURL';
let realmName = baseURL.realmName;   //请求的后台域名
var CancelToken = axios.CancelToken;
var source = CancelToken.source();

const http = axios.create({
    baseURL:realmName,
    timeout: 20000, // 请求超时 20s
    withCredentials: true,
    cancelToken: source.token
})

http.interceptors.request.use(config => {
    //请求之前(可以设置token)
    return config;

},error =>{
    // Message.error(error)
    return Promise.reject(error);

});
http.interceptors.response.use(response => {//数据拿到之后

    return Promise.resolve(response); 

},error => {
    
    if (error.response.status) {
        switch (error.response.status) {                
            // 401: 未登录                
            case 401:                    
                break;
            // 其他错误，直接抛出错误提示
            default:
                // error.response.data.message;
                break;
        }
 
        return Promise.reject(error.response);
    }
});

export default{
    post(url,params){//post请求
        return new Promise((resolve,reject)=>{
            http({
                method:'POST',
                url,
                params,
            }).then(res => {
                resolve(res.data);   
            },err => {
                reject(err.data)        
            })
        });
    },
    get(url,params){//get请求
        return new Promise((resolve,reject)=>{
            http({
                method:'GET',
                url,
                params,
            }).then(res => {
                resolve(res.data);   
            },err => {
                reject(err.data)        
            })
        });
    },

    getBaseURL(){
        return realmName;
    }

}
